<template>
	<z-nav-bar title="快速授课"></z-nav-bar>
	<view class="con">
		<select-student @done="e => selStudentObj = e"></select-student>
		<view class="flex_sbc">
			<view class="teach-tit">
				选择课程
				<text>(请先选择学员)</text>
			</view>
			<view class="chang-button" style="width: 120rpx;" @click="createCourse">新建课程</view>
		</view>
		<view v-if="courseDetail.id" class="course-box flex_sbc">
			<view class="flex_fsc">
				<view style="flex-shrink: 0;">第{{ courseDetail.serialNumber }}课</view>
				<view class="uni-ml-32 u-line-1">{{ courseDetail.name }}</view>
			</view>
			<view class="chang-button" @click="selCourse">修改</view>
		</view>
		<view v-else class="select-student flex_cc" :class="{ 'selectl-course': !selStudentObj.id }" @click="selCourse">
			<image :src="`${setting.oss_pub_domain}/app-img/icon/icon-add-main${selStudentObj.id ? '' : '2'}.png`"></image>
			<text>选择课程</text>
		</view>
	</view>
	<bottom-box :buts="buts" @change="buttonClick"></bottom-box>
</template>

<script setup>
import { addCoursePlan } from '@/api/player.js';
import { onShow } from '@dcloudio/uni-app';
import { getPlayerList } from '@/api/player.js';
import { ref, reactive, getCurrentInstance } from 'vue';
const { proxy: that } = getCurrentInstance();
const eventChannel = that.getOpenerEventChannel()

const courseDetail = ref({}), selStudentObj = ref({})
function selCourse() {
	if (!selStudentObj.value.id) return that.tools.alert('请先选择学员');
	uni.setStorageSync('select-course', {});
	uni.navigateTo({
		url: '/pages/player/course/select?type=1',
		events: {
			selCourse(data) {
				courseDetail.value = data[0];
			}
		}
	});
}

const buts = [
	{
		label: '确定授课',
		bgColor: 'uni-color-main-bg'
	}
];

function buttonClick() {
	if (!selStudentObj.value.id) return that.tools.alert('请选择学员')
	if (!courseDetail.value.id) return that.tools.alert('请选择课程')
	let { relQuestionScheme, serialNumber, duration, name, result, beginTime} = courseDetail.value
	result = JSON.parse(result)
	Object.keys(result).forEach(item => {
		result[item].trainingState = false
		result[item].summaryComment = []
		result[item].trainingPoints = Array.from(
			Array(result[item].trainingPoints.length),
			() => []
		)
	})
	result = JSON.stringify(result)
	
	addCoursePlan({ 
		beginTime,
		relQuestionScheme,
		type: 0,
		serialNumber,
		duration,
		name,
		stuId: selStudentObj.value.id,
		result
	}).then(res => {
		eventChannel.emit('done')
		uni.setStorageSync('edit-course', res)
		uni.redirectTo({
			url: '/pages/course/details/details'
		})
	})
}

function createCourse() {
	if (!selStudentObj.value.id) return that.tools.alert('请先选择学员')
	uni.removeStorageSync('edit-course')
	uni.setStorageSync('player-info', selStudentObj.value)
	uni.navigateTo({
		url: '/pages/player/course/course-edit',
		events: {
			editDone(data) {
				console.log(data);
				courseDetail.value = data
			}
		}
	})
}
</script>

<style lang="scss">
@import 'teach-order.scss';
</style>
